package com.fingard.dsp.bank.directbank.zmh01;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.directbank.gzelink01.GZELINK01Header;
import com.fingard.dsp.bank.directbank.zmh01.util.Sm4Util;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;

public class ZMH01SinglePay extends ZMH01Base implements ISinglePay {
    @Override
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
        RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail(p_req1908);

        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req1908.singleDetail.payAct, "refund");
            if (actItem == null) {
                tmpRetDetail.respCode = "0";
                tmpRetDetail.respInfo = "未找到账号[" + p_req1908.singleDetail.payAct + "]商户配置信息,请检查portfiles/" + p_req1908.reqHeader.bankCode + "/config.xml中'actSet'相关配置!";
                tmpRetDetail.transState = PaymentState.FAIL_Payment;
                tmpRetDetail.payInfoCode = FailCode.E9981;
                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }

            JSONObject jsonRequest = new JSONObject();
            jsonRequest.put("clientid", actItem.merchantId);
            jsonRequest.put("username", actItem.userCode);
            jsonRequest.put("password", actItem.userFlag);

            WriteBankLogLn("加密前token请求参数:" + JSON.toJSONString(jsonRequest));

            String saltKey = getBankConfig().getValueAsString("saltKey");
            WriteBankLogLn("SM4国密算法秘钥(saltKey):" + saltKey);
            if (StringHelper.isNullOrEmpty(saltKey)) {
                tmpRetDetail.respCode = "0";
                tmpRetDetail.respInfo = "SM4国密算法秘钥(saltKey)为空,请检查portfiles/" + p_req1908.reqHeader.bankCode + "/config.xml中'saltKey'相关配置!";
                tmpRetDetail.transState = PaymentState.FAIL_Payment;
                tmpRetDetail.payInfoCode = FailCode.E9981;
                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }
            String tmpTokenSm4 = Sm4Util.encryptEcb(saltKey, JSON.toJSONString(jsonRequest));
            WriteBankLogLn("SM4国密算法加密后token请求参数密文:\r\n" + tmpTokenSm4);

            String getTokenUrl = bankFront.getUrl("getToken");
            WriteBankLogLn2("退费token获取服务地址:" + getTokenUrl);
            if (StringHelper.isNullOrEmpty(getTokenUrl)) {
                tmpRetDetail.respCode = "0";
                tmpRetDetail.respInfo = "退费获取token服务地址为空,请检查config/BankFront.xml中" + p_req1908.reqHeader.bankCode + "'getToken'相关配置!";
                tmpRetDetail.transState = PaymentState.FAIL_Payment;
                tmpRetDetail.payInfoCode = FailCode.E9981;
                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }
            String[] tmpStrRet = sendToBank(null, getTokenUrl + "?param=" + tmpTokenSm4);
            if (tmpStrRet[0].length() == 0) {
                if (tmpStrRet[1].contains("param")) {
                    tmpStrRet[1] = tmpStrRet[1].substring(tmpStrRet[1].indexOf("=") + 1);
                    String tmpTokenResp = Sm4Util.decryptEcb(saltKey, tmpStrRet[1]);
                    WriteBankLogLn("解密后报文明文\r\n:" + tmpTokenResp);

                    JSONObject jsonTokenResp = JSONObject.parseObject(tmpTokenResp);
                    String tokenRespCode = jsonTokenResp.getString("code");
                    if ("0".equalsIgnoreCase(tokenRespCode)) {
                        JSONObject tokenDataResp = jsonTokenResp.getJSONObject("data");
                        String token = tokenDataResp.getString("token");
                        WriteBankLogLn("token获取成功,内容为:" + token);
                        WriteBankLogLn("开始发送退费请求...");

                        JSONObject jsonRefundRequest = new JSONObject();
                        jsonRefundRequest.put("OrderId", p_req1908.singleDetail.recAct);
                        jsonRefundRequest.put("CancelReason", "退费");
                        jsonRefundRequest.put("RefundAmount", p_req1908.singleDetail.payAmount);
                        jsonRefundRequest.put("token", token);

                        WriteBankLogLn("加密前退费请求参数:" + JSON.toJSONString(jsonRefundRequest));

                        String tmpRefundSm4 = Sm4Util.encryptEcb(saltKey, JSON.toJSONString(jsonRefundRequest));
                        WriteBankLogLn("SM4国密算法加密后退费参数密文:\r\n" + tmpRefundSm4);

                        tmpStrRet = sendToBank(tmpRefundSm4, bankFront.getUrl("refundSubmit"));
                        if (tmpStrRet[0].length() == 0) {
                            String tmpRefundResp = Sm4Util.decryptEcb(saltKey, tmpStrRet[1]);
                            WriteBankLogLn("解密后退费报文明文\r\n:" + tmpRefundResp);
                            JSONObject jsonRefundResp = JSONObject.parseObject(tmpRefundResp);

                            tmpRetDetail.respCode = "0";
                            tmpRetDetail.respInfo = jsonRefundResp.getString("msg");
                            tmpRetDetail.transState = jsonRefundResp.getString("code");
                            tmpRetDetail.payInfoCode = jsonRefundResp.getString("code");
                        } else {
                            tmpRetDetail.respCode = "0";
                            tmpRetDetail.respInfo = "退费请求失败:" + tmpStrRet[1];
                            tmpRetDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                            tmpRetDetail.transState = PaymentState.FAIL_Payment;
                            tmpRetDetail.payInfoCode = FailCode.E9981;
                        }
                    } else {
                        tmpRetDetail.respCode = "0";
                        tmpRetDetail.respInfo = "退费获取token失败:" + tokenRespCode + "+" + jsonTokenResp.getString("msg");
                        tmpRetDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                        tmpRetDetail.transState = PaymentState.FAIL_Payment;
                        tmpRetDetail.payInfoCode = FailCode.E9981;
                    }
                }
            } else {
                tmpRetDetail.respCode = "0";
                tmpRetDetail.respInfo = "退费获取token失败:" + tmpStrRet[1];
                tmpRetDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                tmpRetDetail.transState = PaymentState.FAIL_Payment;
                tmpRetDetail.payInfoCode = FailCode.E9981;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        return null;
    }

    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }
}